<template>
    <div class="menu-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>菜单管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加菜单
                    </el-button>
                </div>
            </template>

            <!-- 菜单表格 -->
            <CommonTable :loading="loading" :data="menuTree" :offset="280" table-style="width: 100%" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" default-expand-all>
                <el-table-column prop="name" label="菜单名称" width="200" sortable />
                <el-table-column prop="path" label="路径" sortable />
                <el-table-column prop="icon" label="图标" width="100">
                    <template #default="{ row }">
                        <el-icon v-if="row.icon">
                            <component :is="row.icon" />
                        </el-icon>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="sort_order" label="排序" width="80" sortable />
                <el-table-column prop="is_active" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.is_active ? 'success' : 'danger'">
                            {{ row.is_active ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" sortable />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editMenu(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteMenu(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </CommonTable>
        </el-card>

        <!-- 添加/编辑菜单对话框 -->
        <el-dialog v-model="showAddDialog" :title="editingMenu ? '编辑菜单' : '添加菜单'" width="500px" @closed="resetForm">
            <el-form ref="menuFormRef" :model="menuForm" :rules="menuRules" label-width="80px">
                <el-form-item label="菜单名称" prop="name">
                    <el-input v-model="menuForm.name" />
                </el-form-item>

                <el-form-item label="路径" prop="path">
                    <el-input v-model="menuForm.path" placeholder="例如: /users" />
                </el-form-item>

                <el-form-item label="图标" prop="icon">
                    <el-select v-model="menuForm.icon" placeholder="请选择图标" clearable filterable>
                        <el-option v-for="icon in iconOptions" :key="icon.value" :label="icon.label"
                            :value="icon.value">
                            <span style="display: flex; align-items: center;">
                                <el-icon style="margin-right: 8px;">
                                    <component :is="icon.value" />
                                </el-icon>
                                {{ icon.label }}
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="父菜单" prop="parent_id">
                    <el-tree-select v-model="menuForm.parent_id" :data="parentMenuOptions"
                        :props="{ children: 'children', label: 'name', value: 'id' }" placeholder="请选择父菜单（留空为顶级菜单）"
                        clearable check-strictly />
                </el-form-item>

                <el-form-item label="排序" prop="sort_order">
                    <el-input-number v-model="menuForm.sort_order" :min="0" :max="999" />
                </el-form-item>

                <el-form-item label="状态" prop="is_active">
                    <el-switch v-model="menuForm.is_active" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitMenu">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import CommonTable from '@/components/CommonTable.vue'

const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const editingMenu = ref(null)

const menuTree = ref([])
const allMenus = ref([])

const menuFormRef = ref()

const menuForm = reactive({
    name: '',
    path: '',
    icon: '',
    parent_id: null,
    sort_order: 0,
    is_active: true
})

const menuRules = {
    name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    path: [
        { pattern: /^\//, message: '路径必须以 / 开头', trigger: 'blur' }
    ]
}

// 图标选项
const iconOptions = [
    { label: '用户', value: 'User' },
    { label: '用户组', value: 'UserFilled' },
    { label: '菜单', value: 'Menu' },
    { label: '设置', value: 'Setting' },
    { label: '首页', value: 'House' },
    { label: '文档', value: 'Document' },
    { label: '图表', value: 'DataLine' },
    { label: '监控', value: 'Monitor' },
    { label: '工具', value: 'Tools' },
    { label: '搜索', value: 'Search' },
    { label: '消息', value: 'Message' },
    { label: '邮件', value: 'Message' },
    { label: '位置', value: 'Location' },
    { label: '时间', value: 'Clock' },
    { label: '星星', value: 'Star' },
    { label: '收藏', value: 'Collection' }
]

// 父菜单选项（排除当前编辑的菜单及其子菜单）
const parentMenuOptions = computed(() => {
    if (!editingMenu.value) {
        return menuTree.value
    }

    // 过滤掉当前菜单及其子菜单
    const filterMenus = (menus) => {
        return menus.filter(menu => {
            if (menu.id === editingMenu.value.id) {
                return false
            }
            if (menu.children) {
                menu.children = filterMenus(menu.children)
            }
            return true
        })
    }

    return filterMenus(JSON.parse(JSON.stringify(menuTree.value)))
})

// 获取菜单树
const fetchMenus = async () => {
    loading.value = true
    try {
        const response = await axios.get('/api/menus')
        menuTree.value = response.data.menus

        // 同时获取平铺的菜单列表
        const flatResponse = await axios.get('/api/menus/all')
        allMenus.value = flatResponse.data.menus
    } catch (error) {
        ElMessage.error('获取菜单列表失败: ' + (error.response?.data?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 编辑菜单
const editMenu = (menu) => {
    editingMenu.value = menu
    menuForm.name = menu.name
    menuForm.path = menu.path
    menuForm.icon = menu.icon
    menuForm.parent_id = menu.parent_id
    menuForm.sort_order = menu.sort_order
    menuForm.is_active = menu.is_active
    showAddDialog.value = true
}

// 删除菜单
const deleteMenu = async (menu) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除菜单 "${menu.name}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await axios.delete(`/api/menus/${menu.id}`)
        ElMessage.success('删除成功')
        fetchMenus()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 提交菜单表单
const submitMenu = async () => {
    if (!menuFormRef.value) return

    await menuFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = { ...menuForm }

                if (editingMenu.value) {
                    await axios.put(`/api/menus/${editingMenu.value.id}`, data)
                    ElMessage.success('更新成功')
                } else {
                    await axios.post('/api/menus', data)
                    ElMessage.success('创建成功')
                }

                showAddDialog.value = false
                fetchMenus()
            } catch (error) {
                ElMessage.error((editingMenu.value ? '更新' : '创建') + '失败: ' + (error.response?.data?.message || error.message))
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    editingMenu.value = null
    menuForm.name = ''
    menuForm.path = ''
    menuForm.icon = ''
    menuForm.parent_id = null
    menuForm.sort_order = 0
    menuForm.is_active = true
    menuFormRef.value?.resetFields()
}

onMounted(() => {
    fetchMenus()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

:deep(.el-tree-select .el-select__placeholder) {
    color: #c0c4cc;
}
</style>